﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPython.Compiler;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;

namespace Yugi.Script
{
    public class PythonEngine
    {
        private static PythonEngine current = new PythonEngine();
        public static PythonEngine GetInsitance()
        {
            return current;
        }
        ScriptEngine engine;
        ScriptRuntime runtime;
        ScriptScope scope;
        CompiledCode code;

        private PythonEngine()
        {
            engine = IronPython.Hosting.Python.CreateEngine();
            runtime = engine.Runtime;
            scope = engine.CreateScope();
        }

       
        public bool addSource(string source)
        {
            try
            {
                Compile(source);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        private void Compile(string source)
        {
            ScriptSource script = engine.CreateScriptSourceFromString(source, SourceCodeKind.Statements);
            code = script.Compile();
        }
        private void Compile_File(string source)
        {
            ScriptSource script = engine.CreateScriptSourceFromFile(source);
            code = script.Compile();
        }
        public void SetVariable(string name,object obj)
        {
            scope.SetVariable(name,obj);
        }
        public object GetVariable(string name)
        {
            return scope.GetVariable(name);
        }
        public void SetAssembly(System.Reflection.Assembly ass)
        {
            runtime.LoadAssembly(ass);
        }
        public void Excute(IDictionary<string,object> paramater)
        {
            foreach (var item in paramater.Keys)
            {
                SetVariable(item, paramater[item]);
            }
            runtime.IO.RedirectToConsole();
            code.Execute(scope);

            List<string> l = new List<string>(paramater.Keys);
            for (int i = 0; i < l.Count; i++)
            {
                paramater[l[i]] = GetVariable(l[i]);
            }

        }
    }
}
